﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace CodeGen
{
    class MasterViewAspxCsFileGenerator : CSharpFileGenerator
    {
        public MasterViewAspxCsFileGenerator(string NameSpace, string AspxClassName, string GridViewName, string BllName)
        {
            this.NameSpace = NameSpace;
            this.AspxClassName = AspxClassName;
            this.GridViewName = GridViewName;
            this.BllName = BllName;
        }
        
        string NameSpace;
        string AspxClassName;
        string GridViewName;
        string BllName;

        string GridViewID { get { return "grv" + GridViewName; } }
        string DataSourceID { get { return "ds" + GridViewName; } }

        protected override List<string> GetUsingNameSpaces()
        {
            List<string> lstNS = new List<string>{
                    "System",
                    "System.Collections.Specialized",
                    "System.Web.UI.WebControls",
                    "System.Web.UI.WebControls",
                    "JUtil",
                    "JUtil.Web.Extensions"
                };

            lstNS.Add(NameSpace);

            return lstNS;
        }

        protected override string GetDeclareNameSpaces()
        {
            return NameSpace;
        }

        protected override void ExportClass(StringBuilder sb)
        {
            string ClassPresentation = string.Format("public class {0}", AspxClassName);

            sb.Append(IndentString(ClassPresentation));
            sb.Append("\n");

            sb.Append(StartBlock);

            ExportRowDeleted(sb);
            ExportPageIndexChanged(sb);
            ExportSelectedIndexChanged(sb);
            ExportRowDataBound(sb);
            ExportObjectCreating(sb);

            ExportQueryMaster(sb);
            ExportSetMasterSelectParameters(sb);
            ExportHideDetail(sb);
            ExportCanEdit(sb);
            ExportQueryDetail(sb);

            ExportMasterBLL(sb);

            sb.Append(EndBlock);
        }

        #region ExportRowDeleted
        private void ExportRowDeleted(StringBuilder sb)
        {
            string funcName = string.Format("{0}_RowDeleted", GridViewID);
            sb.Append(IndentString("#region " + funcName));
            sb.Append("\n");

            sb.Append(IndentString("protected void " + funcName  + "(object sender, GridViewDeletedEventArgs e)"));
            sb.Append("\n");

            sb.Append(StartBlock);

            List<string> contents = new List<string>{
                "try                                  ",
                "{                                    ",
                "    if (e.Exception != null)         ",
                "    {                                ",
                "        Log.ReportError(e.Exception);",
                "                                     ",
                "        e.ExceptionHandled = true;   ",
                "    }                                ",
                "    else                             ",
                "    {                                ",
                "        QueryMaster();               ",
                "                                     ",
                "        HideDetail();                ",
                "    }                                ",
                "}                                    ",
                "catch (Exception ex)                 ",
                "{                                    ",
                "    Log.ReportError(ex);             ",
                "}                                    "
            };

            WriteContents(sb, contents);

            sb.Append(EndBlock);

            sb.Append(IndentString("#endregion"));
            sb.Append("\n\n");
        }
        #endregion
        #region ExportPageIndexChanged
        private void ExportPageIndexChanged(StringBuilder sb)
        {
            string funcName = string.Format("{0}_PageIndexChanged", GridViewID);
            sb.Append(IndentString("#region " + funcName));
            sb.Append("\n");

            sb.Append(IndentString("protected void " + funcName + "(object sender, EventArgs e)"));
            sb.Append("\n");

            sb.Append(StartBlock);

            List<string> contents = new List<string>{
                "try                     ",
                "{                       ",
                "    QueryMaster();      ",
                "                        ",
                "    HideDetail();       ",
                "}                       ",
                "catch (Exception ex)    ",
                "{                       ",
                "    Log.ReportError(ex);",
                "}                       "
            };

            WriteContents(sb, contents);

            sb.Append(EndBlock);

            sb.Append(IndentString("#endregion"));
            sb.Append("\n\n");
        }
        #endregion
        #region ExportSelectedIndexChanged
        private void ExportSelectedIndexChanged(StringBuilder sb)
        {
            string funcName = string.Format("{0}_SelectedIndexChanged", GridViewID);
            sb.Append(IndentString("#region " + funcName));
            sb.Append("\n");

            sb.Append(IndentString("protected void " + funcName + "(object sender, EventArgs e)"));
            sb.Append("\n");

            sb.Append(StartBlock);

            List<string> contents = new List<string>{
                "try                                                    ",
                "{                                                      ",
                "    GridView grv = grvMaster;                          ",
                "    OrderedDictionary od = grv.ExtractSelectedValues();",
                "    bool bCanEdit = CanEdit(od);                       ",
                "    QueryDetail(bCanEdit);                             ",
                "}                                                      ",
                "catch (Exception ex)                                   ",
                "{                                                      ",
                "    Log.ReportError(ex);                               ",
                "}                                                      "
            };

            WriteContents(sb, contents);

            sb.Append(EndBlock);

            sb.Append(IndentString("#endregion"));
            sb.Append("\n\n");
        }
        #endregion
        #region ExportRowDataBound
        private void ExportRowDataBound(StringBuilder sb)
        {
            /*
            #region grvMaster_RowDataBound
            protected void grvMaster_RowDataBound(object sender, GridViewRowEventArgs e)
            {
                try
                {
                    GridViewRow row = e.Row;

                    if (row.RowType != DataControlRowType.DataRow) return;

                    OrderedDictionary od = row.ExtractValues();

                    // 仍然可見，只不過能功能變成檢視。
                    ImageButton BtnEdit = (ImageButton)row.GetButton(GridviewCommand.Select);
                    bool bCanEdit = CanEdit(od);
                    BtnEdit.ImageUrl = bCanEdit ? "images/BtnEdit.gif" : "images/BtnSelect.gif";
                    BtnEdit.ToolTip = bCanEdit ? "修改" : "檢視";

                    ImageButton BtnDelete = (ImageButton)row.GetButton(GridviewCommand.Delete);
                    BtnDelete.Visible = CanDelete(od);

                    ImageButton BtnBallot = (ImageButton)row.FindControl("BtnBallot");
                    BtnBallot.Visible = CanBallot(od);
                }
                catch (Exception ex)
                {
            	    Log.ReportError(ex);
                }
            }
            #endregion
             */
            string funcName = string.Format("{0}_RowDataBound", GridViewID);
            sb.Append(IndentString("#region " + funcName));
            sb.Append("\n");

            sb.Append(IndentString("protected void " + funcName + "(object sender, GridViewRowEventArgs e)"));
            sb.Append("\n");

            sb.Append(StartBlock);

            List<string> contents = new List<string>{
                "GridViewRow row = e.Row;                                           ",
                "                                                                   ",
                "if (row.RowType != DataControlRowType.DataRow) return;             ",
                "                                                                   ",
                "OrderedDictionary od = row.ExtractValues();                        ",
                "                                                                   ",
                "//Button BtnEdit = (Button)row.GetButton(GridviewCommand.Select);  ",
                "//bool bCanEdit = CanEdit(od);                                     ",
                "//BtnEdit.ToolTip = bCanEdit ? \"Edit\" : \"View\";                ",
                "//Button BtnDelete = (Button)row.GetButton(GridviewCommand.Delete);",
                "//BtnDelete.Visible = CanDelete(od);                               ",
                "//Button BtnBallot = (Button)row.FindControl(\"BtnBallot\");       ",
                "//BtnBallot.Visible = CanBallot(od);                               "

            };

            WriteContents(sb, contents);

            sb.Append(EndBlock);

            sb.Append(IndentString("#endregion"));
            sb.Append("\n\n");
        }
        #endregion
        #region ExportObjectCreating
        private void ExportObjectCreating(StringBuilder sb)
        {
            /*
             #region BLL ObjectCreating
            protected void dsMaster_ObjectCreating(object sender, ObjectDataSourceEventArgs e)
            {
                e.ObjectInstance = MasterBLL;
            }
            #endregion 
             */

            string funcName = string.Format("{0}_ObjectCreating", DataSourceID);
            sb.Append(IndentString("#region " + funcName));
            sb.Append("\n");

            sb.Append(IndentString("protected void " + funcName + "(object sender, ObjectDataSourceEventArgs e)"));
            sb.Append("\n");

            sb.Append(StartBlock);

            List<string> contents = new List<string>{
                //"throw new NotImplementedException();",
                //"",
                "e.ObjectInstance = MasterBLL;"
            };

            WriteContents(sb, contents);

            sb.Append(EndBlock);

            sb.Append(IndentString("#endregion"));
            sb.Append("\n\n");
        }
        #endregion

        #region ExportQueryMaster
        private void ExportQueryMaster(StringBuilder sb)
        {
            string funcName = "QueryMaster";
            sb.Append(IndentString("#region " + funcName));
            sb.Append("\n");

            sb.Append(IndentString("protected void " + funcName + "(int PageIndex)"));
            sb.Append("\n");

            sb.Append(StartBlock);

            List<string> contents = null;

            contents = new List<string>{
                "grvMaster.PageIndex = PageIndex;",
                "QueryMaster();"
            };

            WriteContents(sb, contents);

            sb.Append(EndBlock);

            sb.Append("\n");

            sb.Append(IndentString("protected void " + funcName + "()"));
            sb.Append("\n");

            sb.Append(StartBlock);

            contents = new List<string>{
                "// setup QueryCondition      ",
                "SetMasterSelectParameters(); ",
                "                             ",
                "// reset index               ",
                "grvMaster.SelectedIndex = -1;",
                "                             ",
                "grvMaster.DataBind();        "
            };
            WriteContents(sb, contents);

            sb.Append(EndBlock);

            sb.Append(IndentString("#endregion"));
            sb.Append("\n\n");
        }
        #endregion
        #region ExportSetMasterSelectParameters
        private void ExportSetMasterSelectParameters(StringBuilder sb)
        {
            string funcName = "SetMasterSelectParameters";
            sb.Append(IndentString("#region " + funcName));
            sb.Append("\n");

            sb.Append(IndentString("protected void " + funcName + "()"));
            sb.Append("\n");

            sb.Append(StartBlock);

            List<string> contents = null;

            contents = new List<string>{
                "throw new NotImplementedException();             ",
                "                                                 ",
                "MasterBLL.SelectParameters.Clear();              ",
                "                                                 ",
                "MasterBLL.SelectParameters[\"ACTIVITY_ID\"] = null;"
            };

            WriteContents(sb, contents);

            sb.Append(EndBlock);
            sb.Append(IndentString("#endregion"));
            sb.Append("\n\n");
        }
        #endregion

        #region ExportHideDetail
        private void ExportHideDetail(StringBuilder sb)
        {
            string funcName = "HideDetail";
            sb.Append(IndentString("#region " + funcName));
            sb.Append("\n");

            sb.Append(IndentString("protected void " + funcName + "()"));
            sb.Append("\n");

            sb.Append(StartBlock);

            sb.Append(EndBlock);

            sb.Append(IndentString("#endregion"));
            sb.Append("\n\n");
        }
        #endregion
        #region ExportCanEdit
        private void ExportCanEdit(StringBuilder sb)
        {
            string funcName = "CanEdit";
            sb.Append(IndentString("#region " + funcName));
            sb.Append("\n");

            sb.Append(IndentString("private bool CanEdit(OrderedDictionary od)"));
            sb.Append("\n");

            sb.Append(StartBlock);

            sb.Append(IndentString("return true;"));

            sb.Append(EndBlock);

            sb.Append(IndentString("#endregion"));
            sb.Append("\n\n");
        }
        #endregion
        #region ExportQueryDetail
        private void ExportQueryDetail(StringBuilder sb)
        {
            string funcName = "QueryDetail";
            sb.Append(IndentString("#region " + funcName));
            sb.Append("\n");

            sb.Append(IndentString("protected void QueryDetail(bool bCanEdit)"));
            sb.Append("\n");

            sb.Append(StartBlock);

            sb.Append(EndBlock);

            sb.Append(IndentString("#endregion"));
            sb.Append("\n\n");
        }
        #endregion

        #region ExportMasterBLL
        private void ExportMasterBLL(StringBuilder sb)
        {
            /*
            private BLL<T_MasterDal> _MasterBLL;
            protected BLL<T_MasterDal> MasterBLL
            {
                get
                {
                    _MasterBLL = _MasterBLL ?? new BLL();
                    return _MasterBLL;
                }
            }
            */
            string funcName = string.Format("MasterBLL");

            sb.Append(IndentString("#region " + funcName));
            sb.Append("\n");

            string BLLField = string.Format("private {0} _{1};", BllName, funcName);
            sb.Append(IndentString(BLLField));
            sb.Append("\n");

            string funcDeclare = string.Format("protected {0} {1}", BllName, funcName);
            sb.Append(IndentString(funcDeclare));
            sb.Append("\n");

            sb.Append(StartBlock);

            List<string> contents = new List<string>{
                "get                                      ",
                "{                                        ",
                "    _MasterBLL = _MasterBLL ?? new "+ BllName +"();",
                "    return _MasterBLL;                   ",
                "}                                        "
            };

            WriteContents(sb, contents);

            sb.Append(EndBlock);

            sb.Append(IndentString("#endregion"));
            sb.Append("\n\n");

        }
        #endregion

        #region WriteContents
        private void WriteContents(StringBuilder sb, List<string> contents)
        {
            foreach (string item in contents)
            {
                string content = item.Trim();

                if (content == "{")
                {
                    sb.Append(StartBlock);
                }
                else if (content == "}")
                {
                    sb.Append(EndBlock);
                }
                else
                {
                    sb.Append(IndentString(content));
                    sb.Append("\n");
                }

            }
        }
        #endregion
    }
}
